package com.mid;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by Lxk on 2019/7/14.
 */
public class Solution103 {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode last = root, curNode = null;
        boolean flag = false;
        queue.add(root);
        List<Integer> list = new ArrayList<>();
        list.add(root.val);
        res.add(list);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur.left != null) {
                queue.add(cur.left);
                curNode = cur.left;
            }
            if (cur.right != null) {
                queue.add(cur.right);
                curNode = cur.right;
            }
            if (cur.equals(last) && !queue.isEmpty()) {
                last = curNode;
                flag = !flag;
                if (flag) {
                    List<Integer> temp = new ArrayList<>();
                    List<TreeNode> que = (List) queue;
                    for (int i = que.size() - 1; i >= 0; i--) {
                        temp.add(que.get(i).val);
                    }
                    res.add(temp);
                } else {
                    List<Integer> temp = new ArrayList<>();
                    List<TreeNode> que = (List) queue;
                    for (int i = 0; i <= que.size() - 1; i++) {
                        temp.add(que.get(i).val);
                    }
                    res.add(temp);
                }
            }
        }
        return res;
    }

}
